package com.wisewin.pose.service;

import com.wisewin.pose.util.JedisUtil;
import com.wisewin.pose.util.wechatOffice.WechatApi;
import com.wisewin.pose.util.wechatOffice.entity.WXTicket;
import com.wisewin.pose.util.wechatOffice.entity.WXToken;
import com.wisewin.pose.util.wechatOffice.security.AESUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WechatService {

    private static final Logger log = LoggerFactory.getLogger(WechatService.class);

    @Autowired
    WechatApi wechatApi;

    /**
     * 获取一个登录二维码
     * @param scene 二维码的唯一标识
     * @return 二维码访问地址
     */

    public String getQRUrl(String scene) {
        try {
            WXTicket ticket = wechatApi.getTicket(getToken(),scene);
            log.debug("ticket:{}",ticket.toString());
            String qrCodeUrl = wechatApi.getQRCodeUrl(ticket.getTicket());
            return qrCodeUrl;
        } catch (Exception e) {
            log.error("获取二维码错误："+e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取公众号token，缓存机制
     * @return
     */
    public String getToken()  {
        String token1 = JedisUtil.get("token");
        if (token1!=null) {
            return AESUtils.decode(token1);
        }else{
            log.info("重新获取token");
            WXToken accessToken = wechatApi.getAccessToken();
            String token = accessToken.getAccess_token();
            String tokenCrypt = AESUtils.encode(token);
            //加密后放入redis
            JedisUtil.setEx("token", tokenCrypt,7000L);
            return token;
        }
    }

    /**
     * 根据code获取openid
     *
     * @param code
     * @return
     */
    public String getOpenIdByCode(String code)  {
        WXToken userToken = wechatApi.getUserToken(code);
        return userToken.getOpenid();
    }
}
